/**
 *@brief WebsocketClient 管理 8258_mesh_gw 之间的消息通信
 */
#pragma once

#include <json/json.h>
#include <mutex>
#include <condition_variable>
#include <cstdint>
#include <deque>

class WebSocketClient {
public:
    enum class State: int {
        Init,
        Connecting,
        Established,
        Closed,
        Destroy,
    };

    /**
    * @brief WebSocket消息与事件处理
    */
    class Delegate {
    public:
        virtual ~Delegate() = default;
        virtual void OnWebSocketMessageReceived(const Json::Value &root) = 0;
        virtual void OnWebSocketStateChanged(State state) {};
    };

    WebSocketClient(const std::string& url, Delegate *delegate);
    int Run();
    void Send(const std::string& msg);
    void OnWrite(void *client);
    void OnReceive(void *client, char *msg) const;
    void SendMessage(const Json::Value& root);
    void OnStateChanged(State state);

private:
    bool mRunning = false;
    Delegate *mDelegate = nullptr;
    std::deque<std::string> mMessageQueue;
    std::mutex mMutex;

    std::string mRemoteAddr;
    uint16_t mRemotePort;
    std::string mRemotePath;
    State mState = State::Init;
};

